package com.csaba.connector.model;

import java.io.Serializable;
import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;

import com.csaba.util.Formatters;

public class Amount implements Serializable
{
	private static final long serialVersionUID = -1605497570847525645L;

	private double amount;
	private Currency currency;

	public Amount( final double amount, final Currency currency )
	{
		this.amount = amount;
		this.currency = currency;
	}

	public Amount( final Amount other )
	{
		this.amount = other.amount;
		this.currency = other.currency;
	}

	public Amount add( final Amount other )
	{
		if ( other == null )
			return this;//TODO implement FX rate conversion here
		if ( !currency.equals(other.getCurrency()) )
			throw new IllegalArgumentException("Currency mismatch! Foreign exchange is not supported yet. (" + currency
					+ " != " + other.currency + ")");
		return new Amount(amount + other.amount, currency);
	}

	public Amount subtract( final Amount other )
	{
		if ( other == null )
			return this;
		if ( !currency.equals(other.getCurrency()) )
			throw new IllegalArgumentException("Currency mismatch! Foreign exchange is not supported yet. (" + currency
					+ " != " + other.currency + ")");
		return new Amount(amount - other.amount, currency);
	}

	public double getAmount()
	{
		return amount;
	}

	public void setAmount( final double amount )
	{
		this.amount = amount;
	}

	public Currency getCurrency()
	{
		return currency;
	}

	public void setCurrency( final Currency currency )
	{
		this.currency = currency;
	}

	@Override
	public String toString()
	{
		final NumberFormat format = Formatters.getCurrencyFormat(currency);
		return format.format(amount) + " " + currency.getCurrencyCode(); //$NON-NLS-1$
	}

	public static boolean isNull( final Amount amount )
	{
		if ( amount == null || amount.amount == 0 )
			return true;
		return false;
	}

	public static void main( final String[] args )
	{
		final Currency forint = Currency.getInstance(Locale.getDefault());
		final Currency euro = Currency.getInstance(Locale.GERMANY);
		System.out.println("Code: " + forint.getCurrencyCode()); //$NON-NLS-1$
		System.out.println("Symbol: " + forint.getSymbol()); //$NON-NLS-1$
		System.out.println("Symbol (EN): " + forint.getSymbol(Locale.GERMAN)); //$NON-NLS-1$
		System.out.println("Description: " + forint.getDefaultFractionDigits()); //$NON-NLS-1$
		System.out.println("Amount: " + new Amount(123123123.45123, forint)); //$NON-NLS-1$
		System.out.println("Amount: " + new Amount(1223123.45123, euro)); //$NON-NLS-1$
		System.out.println("Amount: " + new Amount(1123, euro)); //$NON-NLS-1$

	}
}
